package com.fjnldx.mes.controller.NoAuthenticationRequired;

import com.fjnldx.mes.domain.domainRes.Result;
import com.fjnldx.mes.domain.pojo.User;
import com.fjnldx.mes.domain.pojo.UserLogin;
import com.fjnldx.mes.service.common.CommonService;
import com.fjnldx.mes.utils.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author 11759
 */
@RestController
@RequestMapping("/NoAuthenticationRequired")
@Api(value = "无需权限", tags = "无需权限")
public class NoAuthenticationRequired {
    @Resource
    CommonService commonService;

    @GetMapping("/test")
    public String test() {
        return "test";
    }

    @PostMapping("/Login")
    public Result login(@RequestBody UserLogin data) {
        if (data.getUsername() == null || data.getPassword() == null) {
            return Result.error("请输入账号密码");
        }
        String username = data.getUsername();
        String password = data.getPassword();
        String realPassword = commonService.getPassword(username);
        if (realPassword == null) {
            return Result.error("用户名错误");
        } else if (!realPassword.equals(password)) {
            return Result.error("密码错误");
        } else {
            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            commonService.updateUserUuid(username, uuid);
            return Result.success(JWTUtil.createToken(username, uuid));
        }
    }

    @PostMapping("/logout")
    public Result logout(ServletRequest request) {
        try {
            HttpServletRequest req = (HttpServletRequest) request;
            String token = req.getHeader("Authorization");
            String username = JWTUtil.getUsername(token);
            commonService.updateUserUuid(username, null);
            return Result.success("退出登录");
        } catch (Exception e) {
            return Result.error("当前无用户");
        }
    }

    @PostMapping("/userRegistration")
    @ApiOperation(value = "用户注册", notes = "用户注册")
    public Result userRegistration(@RequestBody User user) {
        return commonService.userRegistration(user);
    }

    @PostMapping("/changePassword")
    @ApiOperation(value = "修改密码", notes = "修改密码")
    public Result changePassword(@RequestBody User user) {
        return commonService.changePassword(user);
    }
}
